package com.weiyirong99.crm.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.tencent.mmkv.MMKV;
import com.weiyirong99.crm.app.R;
import com.weiyirong99.crm.app.adapter.PhoneAdapter;
import com.weiyirong99.crm.app.api.Url;
import com.weiyirong99.crm.app.base.BaseActivity;
import com.weiyirong99.crm.app.bean.PhoneListBean;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class SearchActivity extends BaseActivity {


    private RecyclerView mListView;
    private SearchView mSearchView;
    private List<PhoneListBean.ListDTO> phoneList = new ArrayList<>();
    private PhoneAdapter phoneAdapter;
    private int number = 1;
    private SmartRefreshLayout supplierInquirySrlAnnounce;
    private ClassicsFooter classicFooter;
    private String name;
    private LinearLayout llNoData;
    private ClassicsHeader classicHeader;

    @Override
    public int getLayout() {
        return R.layout.activity_search;
    }

    @Override
    public void initView() {


        mListView = (RecyclerView) findViewById(R.id.mListView);
        mSearchView = (SearchView) findViewById(R.id.mSearchView);
        mSearchView.setOnQueryTextListener(new QueryListener());
        llNoData = (LinearLayout) findViewById(R.id.ll_no_data);
        phoneAdapter = new PhoneAdapter(R.layout.item_phone, phoneList);
        mListView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mListView.setAdapter(phoneAdapter);

        supplierInquirySrlAnnounce = (SmartRefreshLayout) findViewById(R.id.supplier_inquiry_srl_announce);
        classicHeader = (ClassicsHeader) findViewById(R.id.classic_header);
        supplierInquirySrlAnnounce.setEnableRefresh(false);
        supplierInquirySrlAnnounce.setEnableLoadMore(false);
        classicFooter = (ClassicsFooter) findViewById(R.id.classic_footer);
        mSearchView.setIconifiedByDefault(false);
//        设置该SearchView显示搜索图标
        mSearchView.setSubmitButtonEnabled(true);
//        设置该SearchView内默认显示的搜索文字
        mSearchView.setQueryHint("搜索");
        supplierInquirySrlAnnounce.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                number++;
                Log.e("WG", "onLoadMore:     " + number);
                addCust(name, number, 0);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

            }
        });

        phoneAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                PhoneListBean.ListDTO listDTO = phoneList.get(position);
                int id = listDTO.getId();
                Intent intent = new Intent(getActivity(), ClientDetailActivity.class);
                intent.putExtra("customer_id", id);
                startActivity(intent);

            }
        });
    }

    // 搜索文本监听器
    private class QueryListener implements SearchView.OnQueryTextListener {
        // 当内容被提交时执行
        @Override
        public boolean onQueryTextSubmit(String query) {

            name = query;
            addCust(query, number, 0);
            return false;
        }

        // 当搜索框内内容发生改变时执行
        @Override
        public boolean onQueryTextChange(String newText) {
            if (TextUtils.isEmpty(newText)) {
                if (llNoData.getVisibility() == View.VISIBLE) {
                    llNoData.setVisibility(View.GONE);
                }
                phoneList.clear();
                phoneAdapter.notifyDataSetChanged();
                supplierInquirySrlAnnounce.setEnableLoadMore(false);
            } else {

            }
            return true;
        }
    }

    @Override
    public void initParms(Bundle parms) {

    }

    @Override
    public BaseActivity getActivity() {
        return SearchActivity.this;
    }


    private void addCust(String name, int number, int i) {

        long id = MMKV.defaultMMKV().decodeInt("companyId");
        int customer_id = getIntent().getIntExtra("customer_id", 0);
//        long customerid = MMKV.defaultMMKV().decodeInt("customerid");
        String url = Url.BaseUrl + "/api/company/" + id + "/customers/list?current=" + number;
        Map<String, Object> dataMap = new HashMap<>();
//        dataMap.put("group", "1");
        dataMap.put("keyword", name);
        JSONObject jsonObject = new JSONObject(dataMap);
        OkGo.<String>post(url)
                .tag(SearchActivity.this)
                .headers("Authorization", MMKV.defaultMMKV().decodeString("token"))
                .upJson(jsonObject)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        Log.e("WG", "onSuccess: " + response.body());
                        if (response.code() == 200) {
                            PhoneListBean phoneListBean = new Gson().fromJson(response.body(), PhoneListBean.class);
                            List<PhoneListBean.ListDTO> list = phoneListBean.getList();
                            if (number == 1) {
                                if (list.size() == 0) {
                                    llNoData.setVisibility(View.VISIBLE);
                                    supplierInquirySrlAnnounce.setVisibility(View.GONE);
                                } else {
                                    llNoData.setVisibility(View.GONE);
                                    supplierInquirySrlAnnounce.setVisibility(View.VISIBLE);
                                }
                            }

                            for (int i = 0; i < list.size(); i++) {
                                phoneList.add(list.get(i));
                            }
                            getLoadMore(i, true);
                            phoneAdapter.notifyDataSetChanged();
                            supplierInquirySrlAnnounce.setEnableLoadMore(true);
                        } else {
                            try {
                                JSONObject jsonObject = new JSONObject(response.body());
                                String message = jsonObject.getString("message");
                                Log.e("wg", "error: " + message);
                                ts(message);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.e("WG", "onError: ");
                        ts(response.message());
                    }
                });

    }

    private void getLoadMore(int start, boolean flag) {

        supplierInquirySrlAnnounce.finishLoadMore(flag);

    }
}
